//
//  ZGLiveManager.swift
//  ZhangGuang
//
//  Created by 叁拾叁 on 2020/7/20.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import AFNetworking
import SwiftWeb
import HandyJSON

class ZGLiveManager: UIView {
    
    class func postData(url: String, params: Dictionary<String, String>?, imageDatas: Array<UIImage>, successClosure: @escaping (Any) -> Void, failureClosure: @escaping (Error) -> Void) {
        
        let manager = AFHTTPSessionManager()
        manager.responseSerializer = AFJSONResponseSerializer()
        manager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/javascript","text/xml"]
        manager.post(url, parameters: params, headers: nil, constructingBodyWith: { (formData) in
            
            for (_, value) in imageDatas.enumerated() {
                let imageData = value.jpegData(compressionQuality: 0.5)
                let timeStr = Date().format("yyyyMMddHHmmss")
                let fileName = String(format: "%@.jpg" , timeStr)
                formData.appendPart(withFileData: imageData!, name: "file", fileName: fileName, mimeType: "image/jpg")
            }
            
        },progress: { (progress) in
            
            print("progress: \(progress)")
            
        }, success: { (task, res) in
            
            if let r = res {
                print("progress: \(r)")
                successClosure(r)
            }
            
        }) { (task, error) in
            
            print("progress: \(error)")
            failureClosure(error)
        }
    }
    
    class func postInfo(url: String, params: Dictionary<String, Any>?, successClosure: @escaping (Any) -> Void, failureClosure: @escaping (Error) -> Void) {
        
        //afn设置请求体
        let manage = AFHTTPSessionManager()
        do {
            var request:URLRequest = try AFJSONRequestSerializer().request(withMethod: "POST", urlString: url, parameters: nil) as URLRequest
            request.timeoutInterval = 10.0
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.setValue("application/json", forHTTPHeaderField: "Accept")
            request.setValue((params!["token"] as! String), forHTTPHeaderField: "Authorization")
            var p = params
            p?.removeValue(forKey: "token")
            let jsonData: Data = try! JSONSerialization.data(withJSONObject: p as Any, options: .prettyPrinted)
            request.httpBody = jsonData
            let task: URLSessionDataTask = manage.dataTask(with: request, uploadProgress: nil, downloadProgress: nil) { (responseObject, response, error) in
                print("params: ", params ?? "nil", "\n responseObject: ", responseObject, "\n response: ", response ?? "nil", "\n error: ", error ?? "nil")
                if error == nil {
                    successClosure(response!)
                } else {
                    failureClosure(error!)
                }
            }
            task.resume()
        } catch {
            print(error)
        }
        
    }
    
    class func postStartPTZ(url: String, params: Dictionary<String, Any>?, successClosure: @escaping (Any) -> Void, failureClosure: @escaping (Error) -> Void) {
        
        //afn设置请求体
        let manage = AFHTTPSessionManager()
        do {
            var request:URLRequest = try AFJSONRequestSerializer().request(withMethod: "POST", urlString: url, parameters: nil) as URLRequest
            request.timeoutInterval = 10.0
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            
            let postString = "accessToken=\(params!["accessToken"]!)&deviceSerial=\(params!["deviceSerial"]!)&channelNo=\(params!["channelNo"]!)&direction=\(params!["direction"]!)&speed=\(params!["speed"]!)"
            request.httpBody = postString.data(using: .utf8)
            let task: URLSessionDataTask = manage.dataTask(with: request, uploadProgress: nil, downloadProgress: nil) { (responseObject, response, error) in
                print("params: ", params ?? "nil", "\n responseObject: ", responseObject, "\n response: ", response ?? "nil", "\n error: ", error ?? "nil")
                if error == nil {
                    successClosure(response!)
                } else {
                    failureClosure(error!)
                }
            }
            task.resume()
        } catch {
            print(error)
        }
    }
    
    class func postStopPTZ(url: String, params: Dictionary<String, Any>?, successClosure: @escaping (Any) -> Void, failureClosure: @escaping (Error) -> Void) {
        
        //afn设置请求体
        let manage = AFHTTPSessionManager()
        do {
            var request:URLRequest = try AFJSONRequestSerializer().request(withMethod: "POST", urlString: url, parameters: nil) as URLRequest
            request.timeoutInterval = 10.0
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            
            let postString = "accessToken=\(params!["accessToken"]!)&deviceSerial=\(params!["deviceSerial"]!)&channelNo=\(params!["channelNo"]!)&direction=\(params!["direction"]!)"
            request.httpBody = postString.data(using: .utf8)
            let task: URLSessionDataTask = manage.dataTask(with: request, uploadProgress: nil, downloadProgress: nil) { (responseObject, response, error) in
                print("params: ", params ?? "nil", "\n responseObject: ", responseObject, "\n response: ", response ?? "nil", "\n error: ", error ?? "nil")
                if error == nil {
                    successClosure(response!)
                } else {
                    failureClosure(error!)
                }
            }
            task.resume()
        } catch {
            print(error)
        }
    }
    
    class func postGetAccessToken(url: String, params: Dictionary<String, Any>?, successClosure: @escaping (String) -> Void, failureClosure: @escaping (Error) -> Void) {
        
        //afn设置请求体
        let manage = AFHTTPSessionManager()
        do {
            var request:URLRequest = try AFJSONRequestSerializer().request(withMethod: "POST", urlString: url, parameters: nil) as URLRequest
            request.timeoutInterval = 10.0
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            
            let postString = "appKey=\(params!["appKey"]!)&appSecret=\(params!["appSecret"]!)"
            request.httpBody = postString.data(using: .utf8)
            let task: URLSessionDataTask = manage.dataTask(with: request, uploadProgress: nil, downloadProgress: nil) { (responseObject, response, error) in
                print("params: ", params ?? "nil", "\n responseObject: ", responseObject, "\n response: ", response ?? "nil", "\n error: ", error ?? "nil")

                if error == nil {
                    if let d = response as? Dictionary<String, Any>, let dic = d["data"] as? Dictionary<String, Any> {
                        successClosure(dic["accessToken"] as? String ?? "")
                    }
                } else {
                    failureClosure(error!)
                }
            }
            task.resume()
        } catch {
            print(error)
            failureClosure(error)
        }
    }
    
}
